#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define XH(i,a,b) for(int i = a; i < b; ++i)
#define XXH(i,b,a) for(int i = b; i >= a; --i)
#define Module 1000000007
int tInt;ll tll;string tString;char tChar;
vector<int>tIVector;

ll n,p;

ll countEqu(ll x){
  ll ret = 0;
  for(ll i = x - 1; i <= p - 1; ++i){
    tll = (tll * i)%Module;
  }
  /* printf("1 tll = %lld\n",tll); */
  for(ll i = 2; i <= x - 1; ++i){
    tll /= i;
  }
  /* printf("2 tll = %lld\n",tll); */
  ret = tll;
  ll cheng = p - 1;
  ll i = 1;
  for(; i <= n - x;){
    cheng = (cheng * cheng) % Module;
    i *= 2;
  }
  while(i > n - x){
    cheng = cheng / (p - 1);
    --i;
  }
  ret = (ret * cheng) % Module;
  /* printf("3 ret = %lld\n",ret); */
  return ret;
}

void solve(){
  ll equSum = 0, sum = 1;
  for(ll i = 2; i <= min(n , p); ++i){
    equSum =(equSum + countEqu(i)) % Module;
  }
  /* for(ll i = 0; i < n; ++i){ */
  /*   sum = (sum*(p-1)) % Module; */
  /* } */
  printf("sum = %lld, equSum = %lld\n",sum,equSum);
  printf("%lld\n", sum - equSum);
}

int main(){
  #ifndef ONLINE_JUDGE
    auto start_clock = clock();
    //freopen("input.txt","r",stdin);
//  freopen("output.txt","w",stdout);
  #endif
  cin>>n>>p;
  solve();
  
  #ifndef ONLINE_JUDGE
    auto end_clock = clock();
    //cout<<"runtime: "<<end_clock - start_clock<<"ms"<<endl;
  #endif
  return 0;
}
